var express = require("express");
var router = express.Router();
var fs = require("fs");

/* GET home page. */
router.get("/video", function (req, res, next) {
  console.log("video methods");
  /* let head = { "Content-Type": "video/mp4" };
  //需要设置HTTP HEAD
  res.writeHead(200, head);
  //使用pipe
  fs.createReadStream("./assets/bioscope/2021-12-09/ttest.mp4").pipe(res); */
  let path = "./assets/bioscope/2021-12-09/ttest.mp4";
  let stat = fs.statSync(path);
  let fileSize = stat.size;
  let range = req.headers.range;

  // fileSize 3332038

  if (range) {
    //有range头才使用206状态码

    let parts = range.replace(/bytes=/, "").split("-");
    let start = parseInt(parts[0], 10);
    let end = parts[1] ? parseInt(parts[1], 10) : start + 999999;

    // end 在最后取值为 fileSize - 1
    end = end > fileSize - 1 ? fileSize - 1 : end;

    let chunksize = end - start + 1;
    let file = fs.createReadStream(path, { start, end });
    let head = {
      "Content-Range": `bytes ${start}-${end}/${fileSize}`,
      "Accept-Ranges": "bytes",
      "Content-Length": chunksize,
      "Content-Type": "video/mp4",
    };
    res.writeHead(206, head);
    file.pipe(res);
  } else {
    let head = {
      "Content-Length": fileSize,
      "Content-Type": "video/mp4",
    };
    res.writeHead(200, head);
    fs.createReadStream(path).pipe(res);
  }
});

module.exports = router;
